﻿"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub")
    .withAutomaticReconnect() //断线自动重连
    .build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;
connection.on("LoginResponse", function (res) { 
    console.log("LoginResponse=======", res);
    var encodedMsg = "LoginResponse";
    if (res && res.code == 0) {
        encodedMsg = res.msg;
    }  
    var li = document.createElement("li");
    li.textContent = encodedMsg;


    for (var i = 0; i < res.onlineUser.length; i++) {
        li += `<li>${res.onlineUser[i].userName}</li>`;
    } 

    document.getElementById("usersList").appendChild(li);
});

connection.on("GetUsersResponse", function (res) {
    console.log("GetUsersResponse========", res); 
    var _lis = '<li>在线用户</li>'; 
    if (res && res.code == 0) {

        for (var i = 0; i < res.onlineUser.length; i++) {
            _lis += `<li>${res.onlineUser[i].userName}</li>`;
        } 
    }
    document.getElementById("usersList").innerHTML = _lis;
});

connection.on("ReceiveMessage", function (res) { 
    console.log("ReceiveMessage=======", res); 
    var encodedMsg = "";
    if (res && res.code == 0) {
        encodedMsg = res.msg;
    } 
    var li = document.createElement("li");
    li.textContent = encodedMsg;

    console.log("ReceiveMessage=======",encodedMsg);

    document.getElementById("messagesList").appendChild(li);
});

connection.on("SendMessageResponse", function (res) {
    console.log("SendMessageResponse=======", res);
    if (res && res.Code == 0) {
        var li = document.createElement("li");
        li.textContent = res.Msg;
        document.getElementById("messagesList").appendChild(li);

    } else {
        alert(res.Msg);
    }
});

 //自动重连成功后的处理
connection.onreconnected(connectionId => {
         alert(connectionId); 
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});


//获取在线用户
function getUsers() {
    connection.invoke("GetUsers").catch(function (err) {
        return console.error(err.toString());
    });
  
}